﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Business.Crypto
{
    public class Symmetrical
    {
        private static string saltText = "my salt is a string";

        public static byte[] EncryptText(string text, string password)
        {
            //algoritm
            RijndaelManaged myAlg = new RijndaelManaged();

            //step 1: create salt
            byte[] salt = Encoding.ASCII.GetBytes(saltText);

            //step 2: create key
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt);

            //step 3: set key & IV
            myAlg.Key = key.GetBytes(myAlg.KeySize / 8);
            myAlg.IV = key.GetBytes(myAlg.BlockSize / 8);

            //start encrypting
            MemoryStream streamOut = new MemoryStream();
            ICryptoTransform encryptAlgTrans = myAlg.CreateEncryptor();
            CryptoStream cryptoStream = new CryptoStream(streamOut, encryptAlgTrans, CryptoStreamMode.Write);
            
            cryptoStream.Write(GetBytesFromString(text), 0, GetBytesFromString(text).Length);
            cryptoStream.FlushFinalBlock();

            //reading encrypted bytes
            byte[] encryptedBytes = streamOut.ToArray();
            
            //close
            cryptoStream.Close();
            streamOut.Close();

            //return
            //return Encoding.ASCII.GetString(encryptedBytes);
            return encryptedBytes;
        }
        public static string DecryptText(byte[] text, string password)
        {
            RijndaelManaged myAlg = new RijndaelManaged();
            byte[] salt = GetBytesFromString(saltText);

            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt);
            myAlg.Key = key.GetBytes(myAlg.KeySize / 8);
            myAlg.IV = key.GetBytes(myAlg.BlockSize / 8);

            MemoryStream stream = new MemoryStream();
            ICryptoTransform decryptTransfor = myAlg.CreateDecryptor();
            CryptoStream cryptoStream = new CryptoStream(stream, decryptTransfor, CryptoStreamMode.Write);

            cryptoStream.Write(text, 0, text.Length);
            cryptoStream.FlushFinalBlock();

            byte[] decryptedBytes = stream.ToArray();

            return Encoding.ASCII.GetString(decryptedBytes); ;
        }

        public static byte[] GetBytesFromString(string text)
        {
            return Encoding.ASCII.GetBytes(text);
        }
    }
}
